<template>
    <div class="h-full w-full bg-black text-white overflow-hidden relative touch-none">
      <!-- 背景效果 -->
      <div class="absolute top-0 left-0 w-full h-full z-0 overflow-hidden pointer-events-none">
        <div class="gradient-orb top-left"></div>
        <div class="gradient-orb bottom-right"></div>
        <div class="grid-overlay"></div>
      </div>
  
      <!-- 主要内容区域 -->
      <div class="flex flex-col relative z-10 h-full">
        <div class="flex-1 flex flex-col px-6 pt-6 mx-auto w-full h-full max-h-screen relative">
          <!-- 进度条和返回按钮 -->
          <div class="flex items-center mb-8 gap-4">
            <button 
              class="border-none rounded-full w-8 h-8 flex items-center justify-center cursor-pointer transition-colors duration-200" 
              @click="navigation.handleBack"
            >
              <BackIcon :size="10" />
            </button>
            <div class="flex-1">
              <div class="h-4 bg-white/10 rounded overflow-hidden mr-10">
                <div class="progress-fill" :style="ui.progressStyle">
                  <span class="text-xl pr-2 text-black">{{ ui.progressText }}</span>
                </div>
              </div>
            </div>
          </div>
  
          <!-- 滚动内容区域 -->
          <div class="flex-1 overflow-y-auto custom-scrollbar w-full m-auto pb-28">
            <div class="flex-1 flex flex-col justify-between gap-8 will-change-transform pb-4 max-w-[800px] m-auto">
              <!-- 单词展示区域 -->
              <div class="text-center animate-fadeIn">
                <h1 class="text-5xl font-bold mb-2 bg-gradient-to-r from-[#4A99E9] to-[#5C2797] bg-clip-text text-transparent will-change-transform">
                  {{ wordData.currentWord?.content || "..." }}
                </h1>
                <div class="flex items-center justify-center gap-2 mb-4">
                  <button @click="speech.playPronunciation()" class="text-white/70 hover:text-white">
                    <EnglishPronunciationButton />
                  </button>
                  <div class="text-lg text-white/70">
                    {{ wordData.currentWord?.usphone ? `/${wordData.currentWord.usphone}/` : "" }}
                  </div>
                </div>
                <div v-if="!ui.showDefinition" class="flex flex-col items-center gap-2 my-4">
                  <div class="w-20 h-0.5 bg-white/30"></div>
                  <div class="w-12 h-0.5 bg-white/30"></div>
                </div>
                <div v-else class="text-2xl text-white/90 my-4 animate-fadeIn">
                  {{ wordData.currentWord?.definition || "" }}
                </div>
              </div>
  
              <div v-if="wordData.currentWord" class="flex-1 flex flex-col">
                <!-- 例句区域 -->
                <div 
                  v-if="ui.showDefinition && wordData.currentWord?.example?.text"
                  class="bg-white/5 rounded-lg p-6 mb-4 will-change-transform cursor-pointer" 
                  @click="speech.playExampleSentence"
                >
                  <p 
                    class="text-lg leading-relaxed mb-2" 
                    v-html="wordData.highlightedExample"
                  ></p>
                  <p class="text-base text-white/70 animate-fadeIn">
                    {{ wordData.currentWord.example.translation }}
                  </p>
                </div>
  
                <!-- 相关单词区域 -->
                <div 
                  v-if="ui.showDefinition && hasRelatedWords" 
                  class="bg-white/5 rounded-lg p-6 animate-fadeIn will-change-transform"
                >
                  <div class="flex flex-col gap-4">
                    <div 
                      v-for="(relatedWord, index) in displayedRelatedWords" 
                      :key="index" 
                      class="border-b border-white/10 pb-3 last:border-b-0 last:pb-0"
                    >
                      <div class="flex items-center gap-2 mb-1">
                        <span 
                          class="font-semibold text-[#4A99E9] cursor-pointer" 
                          @click="() => speech.playRelatedWord(relatedWord.word)"
                        >
                          {{ relatedWord.word }}
                        </span>
                        <span class="text-sm text-white/60">{{ relatedWord.partOfSpeech }}</span>
                      </div>
                      <div class="text-[0.95rem] text-white/80">{{ relatedWord.definition }}</div>
                    </div>
                  </div>
                  <div v-if="hasMoreRelatedWords" class="mt-4 text-center">
                    <button 
                      class="text-[#4A99E9] text-sm hover:underline"
                      @click="ui.showAllRelatedWords = !ui.showAllRelatedWords"
                    >
                      {{ ui.showAllRelatedWords ? '收起' : `显示全部 (${wordData.currentWord.relatedWords.length})` }}
                    </button>
                  </div>
                </div>
              </div>
            </div>
          </div>
  
          <!-- 底部按钮区域 -->
          <div class="absolute bottom-0 left-0 right-0 flex justify-center py-6 px-6 z-20 w-full">
            <div class="w-full max-w-[800px] m-auto">
              <!-- 未显示释义时的按钮 -->
              <template v-if="wordData.currentWord && !ui.showDefinition">
                <div class="grid grid-cols-3 gap-4">
                  <button 
                    class="py-4 border-none rounded-lg bg-green-600/30 text-white font-semibold text-lg transition-all duration-300 hover:bg-green-600/50" 
                    @click="wordLearning.handleResponse('know')"
                  >
                    认识
                  </button>
                  <button 
                    class="py-4 border-none rounded-lg bg-yellow-600/30 text-white font-semibold text-lg transition-all duration-300 hover:bg-yellow-600/50" 
                    @click="wordLearning.handleResponse('fuzzy')"
                  >
                    模糊
                  </button>
                  <button 
                    class="py-4 border-none rounded-lg bg-red-600/30 text-white font-semibold text-lg transition-all duration-300 hover:bg-red-600/50" 
                    @click="wordLearning.handleResponse('unknown')"
                  >
                    不认识
                  </button>
                </div>
              </template>
              
              <!-- 显示释义时的按钮 -->
              <template v-else-if="wordData.currentWord && ui.showDefinition">
                <div class="grid grid-cols-2 gap-4">
                  <button 
                    class="py-4 border-none rounded-lg bg-blue-600/30 text-white font-semibold text-lg transition-all duration-300 hover:bg-blue-600/50" 
                    @click="wordLearning.handleNextWord"
                  >
                    下一词
                  </button>
                  <button 
                    class="py-4 border-none rounded-lg bg-red-600/30 text-white font-semibold text-lg transition-all duration-300 hover:bg-red-600/50" 
                    @click="wordLearning.handleWrong"
                  >
                    记错了
                  </button>
                </div>
              </template>
              
              <!-- 学习完成时的按钮 -->
              <template v-else>
                <div class="grid grid-cols-1 gap-4">
                  <button 
                    class="py-4 border-none rounded-lg bg-gradient-to-r from-blue-500 to-purple-800 text-white font-semibold text-lg transition-all duration-300 hover:opacity-90"
                    @click="navigation.generateEssay"
                  >
                    生成AI文章
                  </button>
                </div>
              </template>
            </div>
          </div>
        </div>
      </div>
    </div>  
  </template>
  
  <script setup>
  import { ref, computed, reactive, onMounted, onBeforeUnmount, nextTick } from 'vue';
  import { useRouter, useRoute } from 'vue-router';
  import { useModalStore } from '@/stores/modal';
  import BackIcon from '@/components/icons/BackIcon.vue';
  import EnglishPronunciationButton from '@/components/icons/EnglishPronunciationButton.vue';
  import { useSpeechModule } from './composables/useSpeech';
  import { useWordLearning } from './composables/useWordLearning';
  import { useNavigation } from './composables/navigationModule';
  
  // ==================== 常量定义 ====================
  const WORD_STATUS = {
    UNLEARNED: 0,
    KNOWN: 1,
    FUZZY: 2,
    UNKNOWN: 3
  };
  
  // ==================== 状态管理 ====================
  const router = useRouter();
  const route = useRoute();
  const lessonId = computed(() => route.params.id || '未知课程');
  const modalStore = useModalStore();
  
  const wordData = reactive({
    knownQueue: [],
    learningQueue: [],
    currentWord: null,
    
    learningState: {
      totalWords: 0,
      learnedWords: 0,
      currentWordIndex: 0,
      totalVocabularyProgress: {
        totalLearnedWords: 0,
        totalWords: 0
      }
    },
    
    get highlightedExample() {
      const { example } = this.currentWord ?? {};
      if (!example?.text || !example?.highlight) return '';
      
      try {
        // 不区分大小写的替换
        const regex = new RegExp(example.highlight, 'i');
        return example.text.replace(
          regex, 
          match => `<span class='text-[#4A99E9] font-semibold'>${match}</span>`
        );
      } catch {
        return example.text;
      }
    },
  
    get progress() {
      const total = this.knownQueue.length + this.learningQueue.length;
      return total ? (this.knownQueue.length / total * 100) : 0;
    }
  });
  
  const ui = reactive({
    showDefinition: false,
    showAllRelatedWords: false,
    progressText: computed(() => `${Math.round(wordData.progress)}%`),
    progressStyle: computed(() => ({
      width: `${Math.round(wordData.progress)}%`
    }))
  });
  
  // ==================== 计算属性 ====================
  const hasRelatedWords = computed(() => wordData.currentWord?.relatedWords?.length > 0);
  const hasMoreRelatedWords = computed(() => 
    wordData.currentWord?.relatedWords?.length > 3
  );
  const displayedRelatedWords = computed(() => {
    if (!wordData.currentWord?.relatedWords) return [];
    return ui.showAllRelatedWords 
      ? wordData.currentWord.relatedWords 
      : wordData.currentWord.relatedWords.slice(0, 3);
  });
  
  // ==================== 工具函数 ====================
  
  // 添加会话学习记录
  const sessionProgress = reactive({
    learned: 0,
    needsSaving: false
  });
  
  // 初始化各个功能模块
  const speech = useSpeechModule(wordData);
  const navigation = useNavigation(route, router, sessionProgress, wordData);
  const wordLearning = useWordLearning(
    route.params.id, 
    wordData, 
    ui, 
    speech, 
    WORD_STATUS,
    sessionProgress
  );
  
  // ==================== 生命周期钩子 ====================
  onMounted(() => {
    if ('speechSynthesis' in window) {
      window.speechSynthesis.getVoices();
    }
    
    // 保存当前课程 ID 到 modalStore
    if (route.params.id) {
      modalStore.setLastCourse(route.params.id);
    }
    
    wordLearning.loadWordData();
  });
  
  onBeforeUnmount(() => {
    if ('speechSynthesis' in window) {
      window.speechSynthesis.cancel();
    }
  });
  </script>
  
  <style scoped>
  * {
    touch-action: pan-y;
  }
  
  /* 自定义滚动条样式 */
  .custom-scrollbar {
    scrollbar-width: thin;
    scrollbar-color: rgba(255, 255, 255, 0.2) transparent;
    -webkit-overflow-scrolling: touch; /* 增加iOS滚动支持 */
    overscroll-behavior: contain; /* 防止滚动穿透 */
  }
  
  .custom-scrollbar::-webkit-scrollbar {
    width: 6px;
  }
  
  .custom-scrollbar::-webkit-scrollbar-track {
    background: transparent;
  }
  
  .custom-scrollbar::-webkit-scrollbar-thumb {
    background-color: rgba(255, 255, 255, 0.2);
    border-radius: 3px;
  }
  
  .custom-scrollbar::-webkit-scrollbar-thumb:hover {
    background-color: rgba(255, 255, 255, 0.3);
  }
  
  /* 确保内容区域不被底部按钮遮挡 */
  .pb-28 {
    padding-bottom: 7rem !important;
  }
  
  /* 高亮例句中的单词 */
  :deep(span.text-\[#4A99E9\]) {
    color: #4A99E9;
    font-weight: bold;
  }
  
  /* 背景效果 */
  .gradient-orb {
    position: absolute;
    border-radius: 50%;
    filter: blur(70px);
    pointer-events: none;
  }
  
  .top-left {
    top: -10%;
    left: -10%;
    width: 45%;
    height: 45%;
    background: linear-gradient(135deg, rgba(74, 153, 233, 0.2) 0%, rgba(49, 89, 163, 0.07) 100%);
    animation: float 15s ease-in-out infinite alternate;
  }
  
  .bottom-right {
    bottom: -15%;
    right: -15%;
    width: 55%;
    height: 55%;
    background: linear-gradient(225deg, rgba(74, 153, 233, 0.15) 0%, rgba(92, 39, 151, 0.07) 100%);
    animation: float 20s ease-in-out infinite alternate-reverse;
  }
  
  .grid-overlay {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-image: 
        linear-gradient(to right, rgba(48, 51, 54, 0.08) 1px, transparent 1px),
        linear-gradient(to bottom, rgba(48, 51, 54, 0.08) 1px, transparent 1px);
    background-size: 25px 25px;
    opacity: 0.3;
    pointer-events: none;
  }
  
  @keyframes float {
    0% {
      transform: translate(0, 0);
    }
    100% {
      transform: translate(5%, 5%);
    }
  }
  
  .progress-fill {
    height: 100%;
    background: white;
    border-radius: 4rem;
    transition: width 0.3s ease;
    display: flex;
    align-items: center;
    justify-content: flex-end;
  }
  
  @keyframes fadeIn {
    from {
      opacity: 0;
      transform: translateY(10px);
    }
    to {
      opacity: 1;
      transform: translateY(0);
    }
  }
  
  .animate-fadeIn {
    animation: fadeIn 0.3s ease-in-out;
  }
  </style>